package com.wsapi.commons.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.orm.hibernate4.support.OpenSessionInViewFilter;
/**
 * 在原有的基础上增加了添加排除路径，避免不必要的session打开和关闭
 * @author yangyan
 *
 */
public class OpenSessionInViewFilter2 extends OpenSessionInViewFilter {

    private List<String> excludePath = null;

    @Override
    protected void initFilterBean() throws ServletException {
	super.initFilterBean();
	String excludePaths = this.getFilterConfig().getInitParameter(
		"excludePath");
	if (excludePaths != null) {
	    String[] split = excludePaths.split(",");
	    for (String prefix : split) {
		if (prefix.trim().equals("")) {
		    continue;
		}
		if (excludePath == null) {
		    excludePath = new ArrayList<String>();
		}
		excludePath.add(prefix);
	    }
	}
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request,
	    HttpServletResponse response, FilterChain filterChain)
	    throws ServletException, IOException {
	if (excludePath != null) {
	    for (String prefix : excludePath) {
		String path = request.getRequestURI();
		if (path.contains(prefix)) {
		    filterChain.doFilter(request, response);
		    return;
		}
	    }

	}
	super.doFilterInternal(request, response, filterChain);
    }
}
